using Godot;
using System;

[Tool]
public partial class ObstacleGroup : Node2D
{
	[Export] public int Distance
	{
		get => _distance;
		set
		{
			_distance = value>0?value:0;
			if (Engine.IsEditorHint() || IsInsideTree())
			{
				UpdateNodePosition();
			}
		}
	}
	[Export] public int Height
	{
		get => _height;
		set
		{
			_height = value; 
			if (Engine.IsEditorHint() || IsInsideTree())
			{
				UpdateNodePosition();
			}
		}
	}
	
	private int _distance = 200;
	private int _height = 100;
	
	private Obstacle _upObstacle;
	private Obstacle _downObstacle;
	public override void _Ready()
	{
		base._Ready();
		UpdateNodePosition();
	}

	private (int UpY, int DownY) GetObstaclePosition()
	{
		// 获得屏幕大小
		var screenSize = GetViewportRect().Size;
		// 计算障碍物的位置
		// 上障碍物的位置
		var upPositionY = _height - _distance / 2;
		var downPositionY = _height + _distance / 2;
		return (upPositionY, downPositionY);
	}
	private void UpdateNodePosition()
	{
		// 获得屏幕大小
		var screenSize = GetViewportRect().Size;
		Logger.SMsg($"Screen Size: {screenSize}");
		// 计算两个障碍物的位置
		// 上障碍物的位置
		var (upPositionY, downPositionY) = GetObstaclePosition();
		// 下障碍物的位置
		var downPosition = new Vector2(0, downPositionY);
		var upPosition = new Vector2(0, upPositionY);
		foreach (var node in GetChildren())
		{
			var child = (Node2D)node;
			// Godot编辑器中节点还未分配具体类型，因此使用名称进行判断
			switch (child.Name)
			{
				case "UpObstacle":
					child.Position = upPosition;
					break;
				case "DownObstacle":
				{
				   child.Position = downPosition;
					break;
				} 
				case "RayCast2D":
					var rayCast2D = (RayCast2D)child;
					rayCast2D.Position = upPosition;
					rayCast2D.TargetPosition = downPosition;
					break;
				// 其他节点
				default:
					Logger.SMsg("Updating node position: " + child.Name);
					break;
			}
		}
	}
	
}